<template>
  <div class="sign">
    <div class="header bg-color-main">
      <div class="headerCon acea-row row-between-wrapper">
        <div class="left acea-row row-between-wrapper">
          <div class="pictrue"><img :src="userInfo.avatar" /></div>
          <div class="text">
            <div class="line1">{{ userInfo.nickname }}</div>
            <div class="integral acea-row">
              <span>金币: {{ userInfo.integral }}</span>
            </div>
          </div>
        </div>
        <router-link
          :to="'/user/sign_record'"
          class="right acea-row row-middle"
        >
          <div class="iconfont icon-caidan"></div>
          <div>明细</div>
        </router-link>
      </div>
    </div>
    
    <div class="wrapper">
      <div class="list acea-row row-between-wrapper" style="height: 1.6rem;">
        <div class="item" v-for="(item, index) in signSystemList" :key="index">
          <div :class="index + 1 === signSystemList.length ? 'rewardTxt' : ''">
            {{ item.day }}
          </div>
          <div
            class="venus"
            :class="
              (index + 1 === signSystemList.length ? 'reward' : '') +
                ' ' +
                (sign_index >= index + 1 ? 'venusSelect' : '')
            "
          ></div>
          <!-- <div class="num" :class="sign_index >= index + 1 ? 'on' : ''">
            +{{ item.sign_num }}
          </div> -->
        </div>
      </div>
      <!--加在 but 上 on 为已签到-->
      <!-- <div
        class="but bg-color-main"
        :class="userInfo.is_day_sgin ? 'on' : ''"
        @click="goSign"
      >
        {{ userInfo.is_day_sgin ? "已签到" : "立即签到" }}
      </div> -->
      <div style="padding: .3rem .3rem 0; display: flex; justify-content: space-between; align-items: center; border-top: 1px solid #eee;">
        <!-- <div style="width: 100%; text-align: center;">
          <span style="font-weight: bold;">今日已挖出金币</span><span style="font-size: .45rem; padding-left: 3%;">{{ goldCoinSum  }}</span>
        </div> -->
        <div style="font-weight: bold;">今日已挖出金币<div style="font-size: .45rem;">{{ goldCoinSum  }}</div></div>
        <div @click="setShareInfoStatus" class="btn-done bg-color-orange" style="font-size: .26rem; padding: .08rem .05rem; height: auto;">再挖一次</div>
      </div>
      <div class="lock"></div>
    </div>
    <!-- 做任务赚金币 -->
    <div class="wrapper wrapper2" style="padding-bottom: 15px">
      <div class="tip">做任务赚金币</div>
      <div>{{ updateData }}</div>
      <div class="list3">
        <div
          class="item acea-row row-between-wrapper"
          v-for="(item, index) in taskList"
          :key="index"
        >
          <div>
            <div class="name line1">{{ item.name }}</div>
            <div class="data font-color-orange">金币 +{{ item.reward }}</div>
          </div>
            <div class="btn-done" @click="+item.isok ? null : taskHref(item)" :class="[ +item.isok ? 'bg-color-gray' : 'bg-color-main']">{{ +item.isok ? '奖励已发放' : '去完成' }}</div>
        </div>
      </div>
    </div>
    <!-- 金币换福利 -->
    <div class="wrapper wrapper2" style="padding-bottom: 15px; padding-top: .3rem;">
      <div class="tip">金币换福利</div>
      <div class="exchange-list" style="display:flex; justify-content:space-around; flex-wrap: wrap;">
        <div v-for="(item, index) in exchangeList" :key="index" @click="exchange(item.type, item.value)" style="width: 100px; margin-top: .4rem; min-width: 30%;">
          <div :class="exchangeTypeColor[+item.type]" class="font-color-white padding20" style="font-size: .36rem; font-weight: bold; border-radius: 8px; text-align: center;" :style="{backgroundImage: exchangeTypeBg[+item.type]}">{{ item.name }}</div>
          <div :class="exchangeTypeColor[+item.type]" class="font-color-white" style="width: 94%; font-size: .18rem; border-radius: 50px; margin: .12rem auto 0; text-align: center; padding: .05rem 0;">{{ item.value }}金币兑换</div>
        </div>
        <div v-for="(item, index) in privilegeGoldList" :key="index" @click="exchange(0, item.coupon_price, item.id)" style="width: 100px; margin-top: .4rem; min-width: 30%;">
          <div :class="'list-'+index" class="font-color-white padding20" style="font-size: .36rem; font-weight: bold; border-radius: 8px; text-align: center;">
            <span style="font-size: small; font-weight: normal">￥</span>{{ item.coupon_price }}<br/>
            <span style="font-size: .18rem; font-weight: normal">可抵现</span>
          </div>
          <div :class="'list-'+index" class="font-color-white" style="width: 94%; font-size: .18rem; border-radius: 50px; margin: .12rem auto 0; text-align: center; padding: .05rem 0;">{{ item.integral }}金币兑换</div>
        </div>
      </div>
    </div>
    <div class="wrapper wrapper2">
      <div class="tip">已累计签到</div>
      <div class="list2 acea-row row-center row-bottom">
        <div class="item" v-for="(item, index) in signCount" :key="index">
          {{ item || 0 }}
        </div>
        <div class="data">天</div>
      </div>
      <div class="tip2">
        据说连续签到第{{ day }}天可获得超额金币，一定要坚持签到哦~~~
      </div>
      <div class="list3">
        <div
          class="item acea-row row-between-wrapper"
          v-for="(item, index) in signList"
          :key="index"
        >
          <div>
            <div class="name line1">{{ item.title }}</div>
            <div class="data">{{ item.add_time }}</div>
          </div>
          <div class="num font-color-orange">+{{ item.number }}</div>
        </div>
        <router-link
          :to="'/user/sign_record'"
          class="Loads acea-row row-center-wrapper"
          v-if="signList.length > 0"
        >
          点击加载更多
          <div class="iconfont icon-xiangyou acea-row row-center-wrapper"></div>
        </router-link>
      </div>
    </div>
    <div
      class="signTip acea-row row-center-wrapper"
      :class="active === true ? 'on' : ''"
    >
      <div class="signTipLight loadingpic"></div>
      <div class="signTipCon">
        <div class="state" style="font-weight: bold;">挖到 <span style="font-size: .4rem;">{{ integral }}</span> 金币</div>
        <div class="integral">签到成功</div>
        <div class="signTipBnt" @click="close">好的</div>
      </div>
    </div>
    <div class="mask" @touchmove.prevent :hidden="active === false"></div>

    <ShareInfo
      v-on:setShareInfoStatus="setShareInfoStatus"
      :shareInfoStatus="shareInfoStatus"
    ></ShareInfo>
  </div>
</template>
<style scoped>
.Loads .iconfont {
  font-size: 0.25rem;
  margin: 0.02rem 0 0 0.1rem;
}
.sign {
  padding-bottom: 50px;
}
.btn-done {
    width: 1.7rem;
    height: 0.5rem;
    text-align: center;
    line-height: 0.5rem;
    color: #fff;
    border-radius: 0.5rem;
    font-size: 0.27rem;
}
.list-0{
  background: linear-gradient(to right, #57acd4, #1b4ae3);
}
.list-1{
  background: linear-gradient(to right, #ffad7a, #fd6c6d);
}
.list-2{
  background: linear-gradient(to right, #f8dd71, #eca610);
}
.list-3{
  background: linear-gradient(to right, #94d9c8, #379d6e);
}
.list-4{
  background: linear-gradient(to right, #b788cf, #79389f);
}
</style>
<script>
import {
  postSignUser,
  getSignConfig,
  postSignIntegral,
  getTaskList,
  getSignList,
  taskFinish,
  getCoinExchangeList,
  ExchangeDiscount,
  getGoldCoinSum,
  randomExtractAgain,
  getPrivilegeGoldList,
  exchangePrivilegeGold
} from "@api/user";
import { isWeixin } from "@utils/index";
import { wechatEvevt, openShareAll, openShareAppMessage, openShareTimeline } from "@libs/wechat";
import { add } from "@utils/bc";
import ShareInfo from "@components/ShareInfo";
import { getShare } from "@/api/public.js";
import { mapGetters } from "vuex";

export default {
  name: "Sign",
  components: {
    ShareInfo
  },
  props: {},
  data: function() {
    return {
      userInfo: {},
      integral: 0,
      signCount: [],
      sign_index: 0,
      signSystemList: [],
      signList: [],
      page: 1,
      limit: 3,
      active: false,
      day: "",
      taskList: [],
      exchangeList: [],
      exchangeTypeColor: ['', 'bg-color-red', 'bg-color-green', 'bg-color-orange', 'bg-color-gray'],
      exchangeTypeBg: ['', 'linear-gradient(-120deg, #f67a38, #e93323)','linear-gradient(-120deg, #8BC34A, #03ad9d)', 'linear-gradient(-120deg, #FF9800, #FFC107)', 'linear-gradient(-120deg, #777, #333)'],
      goldCoinSum: '',
      shareInfoStatus: false,
      privilegeGoldList: [],
    };
  },
  computed: {   
    ...mapGetters({ shareOK: 'shareOk' }),
    updateData() {
      if (this.shareOK === 'SIGN') {
        this.getGoldCoinSum();
        this.getSignList(); 
        this.signUser();
        this.$store.commit('SHARE_SUCCESS', '');
      }
      return this.shareOK;
    }
  },
  mounted: function() {
    this.signUser();
    this.signConfig();
    this.getTaskList();
    this.getSignList();
    this.getExchangeList();
    this.getGoldCoinSum();
    this.shareConfig();
  },
  methods: {
    setShareInfoStatus: function() {
      this.shareInfoStatus = !this.shareInfoStatus;
    },
    // js给数字补0；num：需要补0的数字，length：长度（补到多少位）；
    PrefixInteger: function(num, length) {
      return (Array(length).join("0") + num).slice(-length).split("");
    },
    //数字转中文
    Rp: function(n) {
      var cnum = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
      var s = "";
      n = "" + n; // 数字转为字符串
      for (var i = 0; i < n.length; i++) {
        s += cnum[parseInt(n.charAt(i))];
      }
      return s;
    },
    // 获取用户信息
    signUser: function() {
      let that = this;
      postSignUser({ sign: 1 }).then(res => {
        res.data.integral = parseInt(res.data.integral);
        var sumSginDay = res.data.sum_sgin_day;
        that.userInfo = res.data;
        that.signCount = that.PrefixInteger(sumSginDay, 4);
        that.sign_index = parseInt(res.data.sign_num);
        that.goSign();
      });
    },
    // 签到配置
    signConfig: function() {
      let that = this;
      getSignConfig().then(res => {
        that.signSystemList = res.data;
        that.day = that.Rp(that.signSystemList.length);
      });
    },
    //  用户签到
    goSign: function() {
      let that = this,
        sumSginDay = that.userInfo.sum_sgin_day;
      if (that.userInfo.is_day_sgin) return;
      postSignIntegral().then(res => {
        that.active = true;
        that.integral = res.data.integral;
        let sign_index = parseInt(that.sign_index + 1);
        that.sign_index =
          sign_index > that.signSystemList.length ? 1 : sign_index;
        that.signCount = that.PrefixInteger(sumSginDay + 1, 4);
        that.userInfo.is_day_sgin = true;
        that.userInfo.integral = add(that.userInfo.integral, res.data.integral);
        that.getTaskList(true);
      }).catch(err => {
        that.$dialog.error(err.msg);
      });
    },
    // 今日获取金币总额
    getGoldCoinSum: function() {
      getGoldCoinSum().then(res => {
        console.log('获取今日金币总数', res);
        this.goldCoinSum = res.data.anumber;
      }).catch(err => {
        this.$dialog.error(err.msg)
      });
    },
    // 分享配置
    shareConfig() {
      getShare().then(res => {
        console.log('分享', res);
        let config = {
          desc: `借你的手气挖金币，金币能当钱花！`,
          title: res.data.data.title,
          link: `${location.href}`,
          imgUrl: `${location.protocol}//${location.hostname}/static/share/sign-share-img.jpg`,
        };
        if (isWeixin()) {
          openShareAppMessage(config, 'sign'); 
          openShareTimeline(config, 'sign');
        }
      });
    },
    // 获取每日任务列表
    getTaskList: function(first) {
      let that = this;
      getTaskList().then(res => {
        console.log('任务列表', res.data.json);
        that.taskList = res.data.json;
        if (first) {
          for (let i in that.taskList) {
            if (that.taskList[i].task_name === 'sign_in') {
              that.finishTask('sign_in', that.taskList[i].reward);
            }
          }
        }
        that.getSignList();
      }).catch(res => {
        that.$dialog.error(res.msg);
      });
    },  
    // 金币兑换列表
    getExchangeList: function() {
      let that = this;
      getCoinExchangeList().then(res => {
        console.log('金币兑换列表', res);
        that.exchangeList = res.data;
      }).catch(res => {
        that.$dialog.error(res.msg);
      });
      getPrivilegeGoldList().then(res => {
        console.log('特权金兑换列表', res);
        that.privilegeGoldList = res.data;
      }).catch(err => {
        that.$dialog.error(err.msg)
      });
    },
    // 兑换优惠额度产品
    exchange: function(type, coin, id) {
      let that = this;
      if (!type) {
        that.$dialog.confirm({
          mes: `确定兑换${coin}元特权金?`,
          opts() {
            exchangePrivilegeGold(id)
              .then(res => {
                console.log('兑换特权金', res);
                that.$dialog.success(res.msg);
                that.signUser();
              }).catch(res => {
                that.$dialog.error(res.msg);
              });
          }
        });
        return;
      }
      // type  1,砍价 || 2,拼团 || 3,参团
      let name=['', 'bargaining','makeup','membership'], title=['', '砍价卡','拼团卡','参团卡'];
      that.$dialog.confirm({
        mes: `确定兑换${title[+type]}1张?`,
        opts() {
          ExchangeDiscount(name[+type], coin)
            .then(res => {
              console.log('兑换福利', res);
              that.$dialog.success(res.msg);
              that.signUser();
            }).catch(res => {
              that.$dialog.error(res.msg);
            });
        }
      });
    },
    // 引导任务跳转
    taskHref: function (item) {
      if (item.task_name == 'sign_in') {
        this.goSign();
        return;
      }
      if (item.task_name == 'use_search') {
        this.$router.push({ path: '/search' });
        return;
      }
      this.$router.push({ path: '/' });
    },
    // 任务完成
    finishTask: function (name, reward) {
      taskFinish(name, reward).then(res => {
        console.log("任务完成", res);
        this.getTaskList();
        this.getSignList();
        this.getGoldCoinSum();
      }).catch(err => {
        this.$dialog.error(err.msg);
      });
    },
    //  获取签到列表;
    getSignList: function() {
      let that = this;
      getSignList(that.page, that.limit).then(res => {
        that.signList = res.data;
      });
    },
    close: function() {
      this.active = false;
    }
  }
};
</script>
